<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Update extends Controller
{

    /**
     * @return Response_Response
     */
    private function getResponse()
    {
        $format = isset($_REQUEST['format'])? $_REQUEST['format'] : 'xml';

        if( $format === 'xml' )
            return new Response_XmlResponse();
        elseif( $format === 'json' )
            return new Response_JsonResponse();
        else
            throw new Exception(sprintf ('Unknown response format "%s"', $format));
    }

    public function action_empty()
	{
        $logger = new Log_RequestLogger(DOCROOT.'logs/request');
        $logger->write();
    }

    public function action_info()
	{
        $response = $this->getResponse();
        $this->response->headers('Content-Type', $response->getContentType());

        $id = isset($_REQUEST['parse_info_id'])? $_REQUEST['parse_info_id'] : NULL;
        $message_id = isset($_REQUEST['message_id'])? $_REQUEST['message_id'] : NULL;

        $logger = new Log_RequestLogger(DOCROOT.'logs/request');
        $logger->write();

        $pi = ORM::factory('ParseInfo', $id);
        if( !$pi->loaded() )
        {
            $this->response->body($response->getError(404, 'Parser not found'));
            return;
        }

        $sql = 'SELECT COUNT(id) AS count, SUM(size) AS size FROM message WHERE parse_info_id = :id';
        if( $message_id ) $sql.= ' AND id > :message_id';
        $query = DB::query(Database::SELECT, $sql);
        $query->param(':id', $id);
        $query->param(':message_id', $message_id);
        $result = $query->execute();

        $size_coeff = 0.14;
        $size = $result->get('size', 0);
        $count = $result->get('count', 0);

        $size = round($size * $size_coeff);

        $this->response->body($response->getUpdateInfo($count, $size, $id));
    }

    public function action_messages()
    {
        $response = $this->getResponse();
        $this->response->headers('Content-Type', $response->getContentType());

        $id = isset($_REQUEST['parse_info_id'])? $_REQUEST['parse_info_id'] : NULL;
        $message_id = isset($_REQUEST['message_id'])? $_REQUEST['message_id'] : NULL;
        $limit = isset($_REQUEST['limit'])? $_REQUEST['limit'] : 1;

        $logger = new Log_RequestLogger(DOCROOT.'logs/request');
        $logger->write();

        $pi = ORM::factory('ParseInfo', $id);

        if( !$pi->loaded() )
        {
            $this->response->body($response->getError(404, 'Parser not found'));
            return;
        }

        $orm = ORM::factory('Message')->and_where('parse_info_id', '=', $id)->order_by('id')->limit($limit);
        if( $message_id ) $orm->and_where('id', '>', $message_id);
        $messages = $orm->find_all();

        if( $messages->count() === 0 and $message_id )
        {
            $test = $orm = ORM::factory('Message')->and_where('parse_info_id', '=', $id)->and_where('id', '=', $message_id)->find_all();
            if( $test->count() === 0 )
            {
                $this->response->body($response->getError(501, 'Message id is more then last id in database'));
                return;
            }
        }

        $messages_array = array();
        foreach($messages as $message)
        {
            $messages_array[] = $message->as_array();
        }

        $this->response->body($response->getMessages($messages_array));
    }

}